<?php

namespace App\Http\Controllers;

use App\Models\Article;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;

class ArticleController extends Controller
{
    public function index(Request $request)
    {
        Log::info('Article index request', [
            'params' => $request->all(),
            'url' => $request->fullUrl(),
            'method' => $request->method()
        ]);
        
        try {
            // 检查数据库连接
            try {
                \DB::connection()->getPdo();
            } catch (\Exception $e) {
                Log::error('Database connection failed', [
                    'error' => $e->getMessage()
                ]);
                throw new \Exception('数据库连接失败：' . $e->getMessage());
            }

            // 检查表是否存在
            if (!Schema::hasTable('article')) {
                Log::error('Article table does not exist');
                throw new \Exception('文章表不存在');
            }

            $query = Article::query();
            
            // 搜索条件
            if ($request->has('title')) {
                $query->where('title', 'like', '%' . $request->title . '%');
            }
            if ($request->has('author')) {
                $query->where('author', 'like', '%' . $request->author . '%');
            }
            if ($request->has('status')) {
                $query->where('status', $request->status);
            }

            $perPage = $request->input('limit', 10);
            $page = $request->input('page', 1);

            $articles = $query->orderBy('sort_order', 'desc')
                             ->orderBy('create_time', 'desc')
                             ->paginate($perPage, ['*'], 'page', $page);
            
            Log::info('Article query successful', [
                'count' => $articles->total(),
                'current_page' => $articles->currentPage(),
                'per_page' => $articles->perPage()
            ]);
            
            return response()->json([
                'code' => 200,
                'msg' => 'success',
                'data' => $articles
            ]);
        } catch (\Exception $e) {
            Log::error('Article query failed', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ]);
            
            return response()->json([
                'code' => 500,
                'msg' => '服务器错误：' . $e->getMessage(),
                'debug' => [
                    'message' => $e->getMessage(),
                    'file' => $e->getFile(),
                    'line' => $e->getLine()
                ]
            ], 500);
        }
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|string|max:255',
            'author' => 'required|string|max:100',
            'content' => 'required|string',
            'points_awarded' => 'required|integer|min:0',
            'status' => 'required|integer|in:0,1',
            'sort_order' => 'integer|min:0'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 400,
                'msg' => $validator->errors()->first()
            ]);
        }

        $article = new Article($request->all());
        $article->save();

        return response()->json([
            'code' => 200,
            'msg' => 'success',
            'data' => $article
        ]);
    }

    public function show($id)
    {
        $article = Article::find($id);
        
        if (!$article) {
            return response()->json([
                'code' => 404,
                'msg' => 'Article not found'
            ]);
        }

        // 增加浏览次数
        $article->increment('view_count');

        return response()->json([
            'code' => 200,
            'msg' => 'success',
            'data' => $article
        ]);
    }

    public function update(Request $request, $id)
    {
        $article = Article::find($id);
        
        if (!$article) {
            return response()->json([
                'code' => 404,
                'msg' => 'Article not found'
            ]);
        }

        $validator = Validator::make($request->all(), [
            'title' => 'string|max:255',
            'author' => 'string|max:100',
            'content' => 'string',
            'points_awarded' => 'integer|min:0',
            'status' => 'integer|in:0,1',
            'sort_order' => 'integer|min:0'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 400,
                'msg' => $validator->errors()->first()
            ]);
        }

        $article->update($request->all());
        $article->save();

        return response()->json([
            'code' => 200,
            'msg' => 'success',
            'data' => $article
        ]);
    }

    public function destroy($id)
    {
        $article = Article::find($id);
        
        if (!$article) {
            return response()->json([
                'code' => 404,
                'msg' => 'Article not found'
            ]);
        }

        $article->delete();

        return response()->json([
            'code' => 200,
            'msg' => 'success'
        ]);
    }
} 